﻿package com.cw.war.ui
{

	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	
	import net.libra.utils.GC;

	/**
	 * @author DanielLu
	 */
	public class BitmapUtils
	{
		private static const MAXIMUN_WIDTH : Number = 2880;
		private static const MAXMUN_HEIGHT : Number = 2880;
		//
		private static const NAME : String = "________map";

		/**
		 * 位图装换成影片剪辑
		 * @param mapClassName	地图的类名
		 */
		public static function bitmapToDisplayObject ( mc : DisplayObject ) : Sprite
		{
			var mapContainer : Sprite = new Sprite ();
			mapContainer.name = NAME;
			// 创建地图影片剪辑
			var mapTemp : Sprite = new Sprite ();
			mapTemp.addChild ( mc );

			// 计算横向竖向需要几个bitmapData对象
			var horizontalCount : int = Math.ceil ( mc.width / MAXIMUN_WIDTH );
			var verticalCount : int = Math.ceil ( mc.height / MAXMUN_HEIGHT );
			var i : int = 0;
			var k : int = 0;

			// 位图块大小
			var bitmapDataWidth : Number = 0;
			var bitmapDataHeight : Number = 0;

			// 开始生成
			for (i = 0; i < verticalCount; i ++)
			{
				// 横向扫描初始化
				mc.x = 0;
				mc.y -= bitmapDataHeight;
				bitmapDataHeight = mc.y + mc.height > MAXMUN_HEIGHT ? MAXMUN_HEIGHT : mc.y + mc.height;
				// 行扫描
				bitmapDataWidth = 0;
				for (k = 0; k < horizontalCount; k ++)
				{
					// 计算要绘制的地图范围
					mc.x -= bitmapDataWidth;
					bitmapDataWidth = mc.x + mc.width > MAXIMUN_WIDTH ? MAXIMUN_WIDTH : mc.x + mc.width;

					//
					var bitmapData : BitmapData = new BitmapData ( bitmapDataWidth , bitmapDataHeight );
					bitmapData.draw ( mapTemp );
					var bitmap : Bitmap = new Bitmap ( bitmapData );
					bitmap.x = - mc.x;
					bitmap.y = - mc.y;
					mapContainer.addChildAt ( bitmap , 0 );
				}
			}
			mapTemp.removeChild ( mc );
			GC ();
			return mapContainer;
		}

		/**
		 * 销毁地图
		 * @param mapMC		要销毁的地图影片剪辑
		 */
		public static function destroyBitmapContainer ( container : Sprite ) : void
		{
			if (container.name == NAME)
			{
				while (container.numChildren > 0)
				{
					var child : DisplayObject = container.getChildAt ( 0 ) as DisplayObject;
					if (child is Bitmap)
					{
						// 销毁位图
						Bitmap ( child ).bitmapData.dispose ();
					}
					container.removeChildAt ( 0 );
				}
				// 垃圾回收
				GC ();
			}
		}
	}
}
